package com.beiding.service.search.impl;

import com.beiding.config.HighlightMapper;
import com.beiding.dao.LocalRoomSearchDao;
import com.beiding.exception.NotFoundException;
import com.beiding.pojo.local.LocalRoom;
import com.beiding.pojo.room.Room;
import com.beiding.service.search.RoomSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;

import java.security.Principal;
import java.util.List;
import java.util.Optional;

@Service
public class RoomSearchServiceImpl implements RoomSearchService {

    private LocalRoomSearchDao roomSearchDao;

    private HighlightMapper highlightMapper;

    @Autowired
    public void setHighlightMapper(HighlightMapper highlightMapper) {
        this.highlightMapper = highlightMapper;
    }

    @Autowired
    public void setRoomSearchDao(LocalRoomSearchDao roomSearchDao) {
        this.roomSearchDao = roomSearchDao;
    }

    @Override
    @Secured("ROLE_LANDLORD")
    public List<Room> search(Principal principal, String q, int page, int pageSize) {

        assert page > 0 && pageSize > 0;
        //查找结果
        HighlightPage<LocalRoom> highlightPage = roomSearchDao.find(q, principal.getName(), new QPageRequest(page - 1, pageSize));

        //将结果高亮处理
        highlightMapper.map(highlightPage);

        return LocalRoom.toRoomList(highlightPage);
    }

/*    @Override
    public boolean exist(Principal principal, String id) {
        return roomSearchDao.findByHolderIdAndId(principal.getName(), id) != null;
    }*/

    @Override
    @Secured("ROLE_LANDLORD")
    public List<Room> myRooms(Principal principal, int page, int pageSize)
    {
        assert page > 0 && pageSize > 0;
        return LocalRoom.toRoomList(roomSearchDao.findByHolderId(principal.getName(), new QPageRequest(page - 1, pageSize)));
    }

    @Override
    @Secured("ROLE_LANDLORD")
    public Room findById(String id) {

        Optional<LocalRoom> optional = roomSearchDao.findById(id);

        if (optional.isPresent()) {
            return LocalRoom.toRoom(optional.get());
        }

        throw new NotFoundException("房源未找到");
    }
}
